package com.ahsjdy.st.stservice.service.impl;

import com.ahsjdy.st.stdao.entity.*;
import com.ahsjdy.st.stdao.mapper.*;
import com.ahsjdy.stcommon.dto.CommodityDTO;
import com.ahsjdy.stcommon.dto.MerchantDTO;
import com.ahsjdy.stcommon.enums.CommoEnum;
import com.ahsjdy.stcommon.enums.MerchantEnum;
import com.ahsjdy.stcommon.enums.OrderEnum;
import com.ahsjdy.stcommon.exception.BizException;
import com.ahsjdy.stcommon.holder.PageHolder;
import com.ahsjdy.stcommon.util.DateUtils;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author xuetao wang
 * @Date 2020/1/4
 */
@Service
public class MerchantServiceImpl extends BaseService {

    @Autowired
    private MerchantMapper merchantMapper;

    @Autowired
    private AreaMapper areaMapper;

    @Autowired
    private CommodityMapper commodityMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private SkuMapper skuMapper;

    public void add(String merchantName, String pictureName, int areaId, String phone, String openId) {
        Merchant merchant = new Merchant();
        merchant.setAreaId(areaId);
        merchant.setCreateTime(new Date());
        merchant.setMerchantName(merchantName);
        merchant.setModifyTime(merchant.getCreateTime());
        merchant.setOpenId(openId);
        merchant.setPhone(phone);
        merchant.setPictureName(pictureName);
        merchant.setStatus(0);
        merchantMapper.insert(merchant);
    }

    public void modifyInfo(String merchantName, String pictureName, String phone, String openId) {
        Merchant merchant = merchantMapper.getByOpenId(openId);
        merchant.setMerchantName(merchantName);
        merchant.setModifyTime(new Date());
        merchant.setPhone(phone);
        if (StringUtils.isNotBlank(pictureName)) {
            merchant.setPictureName(pictureName);
        }

        merchantMapper.updateByPrimaryKeySelective(merchant);
    }

    public void changeMerchantStatus(int merchantId, int newStatus) {
        Merchant merchant = merchantMapper.selectByPrimaryKey(merchantId);
        if (null == merchant) {
            throw new BizException("商家不存在");
        }

        if (merchant.getStatus() == newStatus) {
            return;
        }

        int rows = merchantMapper.updateStatus(merchantId, merchant.getStatus(), newStatus);
        if (1 != rows) {
            throw new BizException("审核失败");
        }

    }

    public PageHolder listMerchant(String merchantName, Integer areaId,
                             Integer status, Integer currentPage, Integer pageSize) {

        merchantName = StringUtils.isBlank(merchantName) ? null : merchantName;

        int total = merchantMapper.countMerchant(merchantName, status, areaId);
        PageHolder pageHolder = PageHolder.build(currentPage, total, pageSize);

        List<Merchant> merchants = merchantMapper.listMerchant(merchantName, status, areaId, pageHolder.getOffset(), pageSize);

        List<MerchantDTO> dtos = new ArrayList<>(merchants.size());
        for (Merchant merchant : merchants) {
            MerchantDTO merchantDTO = new MerchantDTO();
            dtos.add(merchantDTO);

            merchantDTO.setAreaId(merchant.getAreaId());
            merchantDTO.setAreaName(areaMapper.selectByPrimaryKey(merchant.getAreaId()).getAreaName());
            merchantDTO.setCreateTime(DateUtils.dateToString(merchant.getCreateTime(), "yyyy-MM-dd"));
            merchantDTO.setMerchantName(merchant.getMerchantName());
            merchantDTO.setOpenId(merchant.getOpenId());
            merchantDTO.setPhone(merchant.getPhone());
            merchantDTO.setId(merchant.getId());
            merchantDTO.setPictureUrl(merchant.getPictureName());
            merchantDTO.setStatus(merchant.getStatus());
        }

        pageHolder.setData(dtos);
        return pageHolder;
    }

    @Transactional(rollbackFor = Exception.class)
    public void addCommodity(String skuInfo, String commName, String openId, String price, String pictureName, String remark) {
        Merchant merchant = merchantMapper.getByOpenId(openId);
        checkMerchant(merchant);

        Commodity commodity = new Commodity();
        commodity.setCommName(commName);
        commodity.setCreateTime(new Date());
        commodity.setMerchantId(merchant.getId());
        commodity.setModifyTime(commodity.getCreateTime());
        commodity.setOriginalPrice(price);
        commodity.setPrice(price);
        commodity.setRemark(remark);
        commodity.setStatus(0);
        commodity.setPictureName(pictureName);
        commodity.setStock(0);

        commodityMapper.insert(commodity);

        //添加sku
        if (StringUtils.isBlank(skuInfo)) {
            return;
        }

        List<Sku> skus = JSON.parseArray(skuInfo, Sku.class);
        for (Sku sku : skus) {
            sku.setCommodityId(commodity.getId());
            sku.setCreateTime(new Date());
            sku.setMerchantId(merchant.getId());

            skuMapper.insert(sku);
        }
    }

    public List<CommodityDTO> listCommodity(String openId) {
        Merchant merchant = merchantMapper.getByOpenId(openId);

        List<Commodity> commodities = commodityMapper.listCommodity(merchant.getId(), null);
        List<CommodityDTO> dtos = new ArrayList(commodities.size());

        for (Commodity comm : commodities) {
            CommodityDTO dto = new CommodityDTO();
            dtos.add(dto);

            int sales = orderDetailMapper.countSales(comm.getId(), OrderEnum.已送达.getK());

            dto.setCommName(comm.getCommName());
            dto.setCreateTime(DateUtils.dateToString(comm.getCreateTime(), "yyyy-MM-dd"));
            dto.setId(comm.getId());
            dto.setMerchantId(comm.getMerchantId());
            dto.setOriginalPrice(comm.getOriginalPrice());
            dto.setPictureUrl(pictureUrl + comm.getPictureName());
            dto.setPrice(comm.getPrice());
            dto.setRemark(comm.getRemark());
            dto.setStatus(comm.getStatus());
            dto.setStatusValue(CommoEnum.getEnum(comm.getStatus()).getV());
            dto.setSales(sales);
        }

        return dtos;
    }

    @Transactional(rollbackFor = Exception.class)
    public void changeCommodityStatus(String openId, int commodityId, int newStatus) {
        Merchant merchant = merchantMapper.getByOpenId(openId);

        Commodity commodity = commodityMapper.selectByPrimaryKey(commodityId);
        if (!commodity.getMerchantId().equals(merchant.getId())) {
            throw new BizException("无权操作");
        }

        if (newStatus == commodity.getStatus()) {
            return;
        }

        int rows = commodityMapper.updateStatus(commodity.getId(), newStatus, commodity.getStatus());
        if (1 != rows) {
            throw new BizException("操作失败");
        }
    }

    public MerchantDTO loadMerchant(String openId) {
        Merchant merchant = merchantMapper.getByOpenId(openId);
        Area area = areaMapper.selectByPrimaryKey(merchant.getAreaId());

        MerchantDTO merchantDTO = new MerchantDTO();
        merchantDTO.setStatus(merchant.getStatus());
        merchantDTO.setPictureUrl(pictureUrl + merchant.getPictureName());
        merchantDTO.setId(merchant.getId());
        merchantDTO.setPhone(merchant.getPhone());
        merchantDTO.setOpenId(merchant.getOpenId());
        merchantDTO.setMerchantName(merchant.getMerchantName());
        merchantDTO.setCreateTime(DateUtils.dateToString(merchant.getCreateTime()));
        merchantDTO.setAreaName(area.getAreaName());
        merchantDTO.setAreaId(merchant.getAreaId());
        merchantDTO.setStatusValue(MerchantEnum.getEnum(merchant.getStatus()).getV());

        return merchantDTO;
    }


    @Transactional(rollbackFor = Exception.class)
    public void changeStatusByMerchant(String openId, int newStatus) {
        Merchant merchant = merchantMapper.getByOpenId(openId);
        if (merchant.getStatus() == newStatus) {
            return;
        }

        if (!openId.equals(merchant.getOpenId())) {
            throw new BizException("无权操作");
        }

        if (newStatus == MerchantEnum.营业中.getK()) {
            if (merchant.getStatus() == MerchantEnum.禁用.getK()) {
                throw new BizException("店铺已被禁用，请联系客服");
            }
            if (merchant.getStatus() == MerchantEnum.申请中.getK()) {
                throw new BizException("店铺还在申请中，暂时不能营业");
            }
        }

        int rows = merchantMapper.updateStatus(merchant.getId(), merchant.getStatus(), newStatus);
        if (1 != rows) {
            throw new BizException("操作失败");
        }

    }



}
